package com.northpool.operator.common.json;

import cn.hutool.core.lang.Opt;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.utils.StpOperatorHelper;

@OperatorInfo(ref = "JsonFormatterOperator", name = "JSON格式化")
@OutputParams({
        @OutputParam(ref = "formatted", name = "格式化结果")
})
public class JsonFormatterOperator extends StpOperatorHelper {


    @InputParams({
            @InputParam(ref = "jsonStr", name = "原始JSON字符串", desc = "JSON字符串, 如: {\"name\":\"test\"}", required = true)
    })
    public JsonFormatterOperator() {
    }

    public static void main(String[] args) throws Exception {
        OperatorTestBuild.execute(JsonFormatterOperator.class, TestParamBuilder.aBuilder()
                .param("jsonStr", "{\"name\":\"test\"}")
                .build());
    }

    @Override
    public void execute(ParamTool params) {
        String jsonStr = Opt.ofBlankAble(params.getStr("jsonStr"))
                .orElseThrow(() -> new IllegalArgumentException("jsonStr 不能为空"));

        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String formatted = JSONObject.toJSONString(jsonObject, SerializerFeature.PrettyFormat);
        this.result("formatted", formatted);
    }
}